package com.springcloud.eshop.datasync.rabbitmq.strategy;

import com.alibaba.fastjson.JSON;
import com.springcloud.eshop.datasync.enums.DataTypeEnum;
import com.springcloud.eshop.datasync.enums.EventTypeEnum;
import com.springcloud.eshop.datasync.rabbitmq.factory.DataChangeHandlerFactory;
import com.springcloud.eshop.datasync.service.EshopProductService;
import com.springcloud.eshop.entity.Product;
import com.springcloud.eshop.message.AggrDataChangeMessage;
import com.springcloud.eshop.message.DataChangeMessage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Set;

/**
 * @Desc:
 * @Date: 2020-07-02
 * @Version:v1.0
 */
@Service
public class ProductDataChangeStrategy extends BaseDataChangeHandler implements InitializingBean {
    private Logger logger = LoggerFactory.getLogger(ProductDataChangeStrategy.class);

    @Autowired
    private EshopProductService eshopProductService;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean handler(DataChangeMessage dataChangeMessage) {
        String eventType = dataChangeMessage.getEventType();
        boolean addOrUpdate = EventTypeEnum.isAddOrUpdate(eventType);
        if (addOrUpdate) {
            addProductId(dataChangeMessage.getId());
            Set<Long> productIdSet = getProductIdSet();
            if (getProductIdSet().size() < 2) {
                logger.info("ProductDataChangeStrategy.handler process, 变更商品Id集合不足，继续等待 ,dataChangeMessage : {}", dataChangeMessage);
                return true;
            }
            // 批量获取商品数据
            List<Product> products = eshopProductService.selectProducts(StringUtils.join(productIdSet, ","));
            logger.info("ProductDataChangeStrategy.handler process, 批量获取商品数据成功，products : {}", JSON.toJSONString(dataChangeMessage));
            // 批量设置redis数据
            if (CollectionUtils.isNotEmpty(products)) {
                for (Product product : products) {
                    jedisPool.getResource().set(getRedisKey(product.getId()), JSON.toJSONString(product));
                }
            }
            clearProductIdSet();
        } else if (EventTypeEnum.DELETE.getType().equals(eventType)) {
            jedisPool.getResource().del(getRedisKey(dataChangeMessage.getId()));
        }
        addMessage(new AggrDataChangeMessage("product", dataChangeMessage.getId()));
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        DataChangeHandlerFactory.register(DataTypeEnum.PRODUCT.getType(), this);
    }

    @Override
    public String getRedisKey(long id) {
        return "product_detail_" + id;
    }
}
